<template>
    <Dialog v-model="dialogVisible" width="500px" title="修改root密码" maxHeight="100px" @close="closeHandle">
        <el-form ref="ruleFormRef" :model="formData" :rules="formRules" label-width="80px" class="">
            <el-form-item label="旧密码" prop="password_old" required>
                <el-input v-model="formData.password_old" placeholder="请输入" clearable maxlength="120" />
            </el-form-item>
            <el-form-item label="新密码" prop="password_new" required>
                <el-input v-model="formData.password_new" placeholder="请输入" clearable maxlength="120" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="closeHandle">关闭</el-button>
            <el-button type="primary" :loading="loading" @click="saveHandle(ruleFormRef)">提交</el-button>
        </template>
    </Dialog>
</template>
<script setup lang='ts'>
import { ref, computed, watch, defineEmits, reactive, onMounted } from 'vue'
import { setUpdateRootKeyAPI } from "@/api/systemMonitor"
import { propTypes } from '@/utils/propTypes'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['update:modelValue'])

const props = defineProps({
    modelValue: propTypes.bool.def(false),
})
//默认表单
const defaultFormData = {
    password_old: "",
    password_new: "",
}

const loading = ref(false)

const formData = reactive({
    ...defaultFormData
})

const ruleFormRef = ref<FormInstance>()
const formRules = reactive<FormRules>({
    password_old: [
        { required: true, message: '此项必填', trigger: 'blur' },
    ],
    password_new: [
        { required: true, message: '此项必填', trigger: 'blur' },
    ],

})
onMounted(() => {
})


//弹出框状态
const dialogVisible = ref(props.modelValue)

watch(() => props.modelValue, (newVal) => {
    dialogVisible.value = newVal;
})
//提交
const saveHandle = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            loading.value = true;
            setUpdateRootKeyAPI({
                ...formData,
            }).then(() => {
                ElMessage.success("修改密码成功")
                closeHandle()
            }).finally(() => {
                loading.value = false;
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
//关闭
const closeHandle = () => {
    dialogVisible.value = false;
    //初始化数据
    Object.assign(formData, defaultFormData);
    emit('update:modelValue', dialogVisible)
}

</script>
<style lang="less" scoped>

</style>